﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace MvcControlsToolkit
{
    public class Accordion: Control
    {
        public bool IsCached
        {
            get
            {
                if (Attributes.ContainsKey("cache"))
                    return bool.Parse(Attributes["cache"]);
                else return false;
            }
            set { Attributes["cache"] = value.ToString().ToLower(); }
        }

        public string LoadingText
        {
            get { return GetString("spinner"); }
            set { SetString("spinner", value); }
        }

        public string AdditionalAttributes { get; set; }
        public List<AccordionItem> AccordionItems { get; set; }

        public string OnChangeStart 
        {
            get { return Attributes["changestart"]; }
            set { Attributes["changestart"] = value; }
        }

        public string OnChange
        {
            get { return Attributes["change"]; }
            set { Attributes["change"] = value; }
        }

        public string OnCreate
        {
            get { return Attributes["create"]; }
            set { Attributes["create"] = value; }
        }

        public Accordion(string name): base(name)
        {
            AccordionItems = new List<AccordionItem>();
            LoadingText = "Loading...";
        }


        /// <summary>
        /// Add a new AccordionItem
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Accordion AddItem(AccordionItem item)
        {
            AccordionItems.Add(item); 
            return this;
        }

        public override string GetJScript()
        {
            var result = new StringBuilder();

            foreach (string key in Attributes.Keys)
            {
                result.AppendFormat(", {0}: {1}", key, Attributes[key]);
            }

            /* Disable Tabs */
            var selectedIndex = getSelected();
            result.Append(", activate: " + selectedIndex);

            /* Disable Tabs */
            var disabledIndexes = getDisabledList();
            if (!string.IsNullOrEmpty(disabledIndexes))
                result.Append(", disabled: " + disabledIndexes);

            if (result.Length > 0)
                result.Remove(0, 1);

            return "var " + Name + " = $(\"#" + Name + "\").accordion({" + result + "});";
        }

        public override string GetHtml()
        {
            var sb = new StringBuilder();
            int index = 0;

            foreach (AccordionItem item in this.AccordionItems)
            {
                string tabContent = String.Empty;

                switch (item.ContentType)
                {
                    case ContentType.Static:
                        tabContent = item.HTMLContent;
                        item.Action = "#accordianItem_" + index;
                        break;
                    case ContentType.PartialView:
                        tabContent = ControlManager.RenderPartialToString(Helper, item.PartialViewName, item.PartialViewModel, item.PartialViewData);
                        item.Action = "#accordianItem_" + index;
                        break;
                    case ContentType.RemoteAction:
                        tabContent = this.LoadingText;
                        throw new NotImplementedException();
                        break;
                }
                sb.AppendLine(item.ToString());

                sb.AppendLine("<div id=\""+item.Action+"\" content-type=\"" + item.ContentType + "\">" + tabContent + "</div>");

                index++;
            }
            return string.Format("<div id=\"" + this.Name + "\" is-cached=\"{0}\">\r\n{1}\r\n</div>", IsCached, sb.ToString());
        }


        private int getSelected()
        {
            for (int i = 0; i < this.AccordionItems.Count; i++)
                if (this.AccordionItems[i].Selected)
                    return i;

            return -1;
        }


        private string getDisabledList()
        {
            var result = new List<int>();
            for (int i = 0; i < this.AccordionItems.Count; i++)
                if (!AccordionItems[i].Enabled)
                    result.Add(i);

            if (result.Count != 0)
            {
                var serializer = new JavaScriptSerializer();

                return serializer.Serialize(result.ToArray());
            }
            return
                null;
        }
    }
}
